﻿using PBO.Network;
using PBO.RoomClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PBO.Forms.NetworkForm.BattleForm.FourPlayer
{
    public class AgentFourPlayerForm : FourPlayerClientForm
    {
        private int _identity;
        private bool _asHost;
        private FourPlayerFormCallback _callback;

        public AgentFourPlayerForm(int identity, string address, string name, bool asHost, FourPlayerFormCallback callback)
            : base(address, name)
        {
            //InitializeComponent();

            _identity = identity;
            _asHost = asHost;
            _callback = callback;
            if (asHost)
            {
                Player1Button.Enabled = false;
                Player2Button.Enabled = false;
                Player3Button.Enabled = false;
                Player4Button.Enabled = false;
                _myPosition = 1;
                this.ClientSize = new System.Drawing.Size(274, 183);
            }
            else
            {
                //StartButton.Hide();
            }
        }
        protected override void ConnectServer()
        {
            _client.OnServerClosed += ServerClosed;
            _client.SetPort((int)ServerPort.FourPlayerAgentServerPort);
            base.ConnectServer();
        }
        protected override void Connected()
        {
            _client.Logon(_identity);
        }
        protected override void SetPosition(byte position, string player)
        {
            bool enable = (string.IsNullOrEmpty(player));
            if (_asHost)
                enable = false;
            SetButton(Controls.Find(string.Format("Player{0}Button", position), false)[0], enable, player);
        }
        protected override void OnSetPosition()
        {
            //if (_asHost)
            //    StartButton.Enabled = FullPlayer; 
        }
        protected override void StartBattle(int identity)
        {
            if (_myPosition != 0)
            {
                _callback(identity, _myPosition);
                ServerClosed();
            }
        }

        private void ServerClosed()
        {
            Invoke(new NetworkLib.VoidFunctionDelegate(Close));
        }

        private void StartButton_Click(System.Object sender, System.EventArgs e)
        {
            _client.StartBattle();
        }

        private bool FullPlayer
        {
            get
            {
                if (Player2Button.Text.Length == 0)
                    return false;
                if (Player3Button.Text.Length == 0)
                    return false;
                if (Player4Button.Text.Length == 0)
                    return false;
                return true;
            }
        }

        protected override void OnEscape()
        {
            if (_asHost)
                _client.Close();
        }

    }
}
